const net = require('net');

const server = net.createServer();

let clientName = 0;
let clientArr = {};
const port = 9527;
const host = 'localhost';
server.on('connection', (client) => {
    
    client.name = clientName;
    clientArr[client.name] = client;
    console.log(clientName + '上线了。');
    broadcast(clientName + '上线了。');
    
    client.on('data', (data) => {
        broadcast(data.toString(), client);
    })
    client.on('error', (err) => {
        console.log('client error' + err);
        client.end();
    })
    client.on('close', () => {
        console.log(client.name + '离开了。');
        delete clientArr[client.name];
        broadcast(client.name + '离开了。');
    })
    clientName++;
})
server.on('error', (err) => {
    console.log('server err');
    throw err;
})

function broadcast(msg, targetClient) {
    for (const key in clientArr) {
        if (!targetClient) {
            clientArr[key].write('系统提示：' + msg);
        } else {
            clientArr[key].write(targetClient.name + '说：' + msg);
        }
    }
}

server.listen(port, host, () => {
    console.log('server start');
})